package com.milotnt.controller;

import com.milotnt.pojo.CommunityCommentEntity;
import com.milotnt.pojo.CommunityPostEntity;
import com.milotnt.pojo.MemberEntity;
import com.milotnt.service.CommunityCommentService;
import com.milotnt.service.CommunityPostService;
import com.milotnt.vo.CommunityPostVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/community")
public class CommunityController {

    @Autowired
    private CommunityPostService communityPostService;

    @Autowired
    private CommunityCommentService communityCommentService;

    // 使用配置文件指定上传路径
    @Value("${upload.path.community}")
    private String communityUploadPath;

    // 跳转社区页面
    @RequestMapping("/toCommunity")
    public String toCommunity(Model model, HttpSession session) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        List<CommunityPostVo> postList = communityPostService.getAllPosts();

        for (CommunityPostVo post : postList){
            post.setComments(communityCommentService.selectCommentsById(post.getId()));
        }

        model.addAttribute("postList", postList);
        return "community";
    }

    // 发布帖子
    @RequestMapping("/addPost")
    public String addPost(CommunityPostEntity post, MultipartFile image, HttpSession session) throws IOException {
        MemberEntity member = (MemberEntity) session.getAttribute("user");
        if (member == null) {
            return "redirect:/userLogin";
        }
        post.setMemberId(member.getMemberAccount());
        post.setMemberName(member.getMemberName());
        post.setCreateTime(new Date());

        try {
            // 处理图片上传
            if (image != null && !image.isEmpty()) {
                // 验证文件类型
                if (!isValidImageFile(image)) {
                    throw new IllegalArgumentException("只允许上传图片文件");
                }

                // 确保上传目录存在
                File uploadDir = new File(communityUploadPath);
                if (!uploadDir.exists()) {
                    boolean created = uploadDir.mkdirs();
                    log.info("创建上传目录: {} -> {}", communityUploadPath, created);
                }

                // 生成唯一文件名
                String fileName = UUID.randomUUID() + "." +
                        getFileNameExtension(image.getOriginalFilename());
                String filePath = communityUploadPath + fileName;

                // 保存文件
                File destFile = new File(filePath);
                image.transferTo(destFile);
                log.info("文件上传成功: {} -> {}", image.getOriginalFilename(), filePath);

                // 设置正确的相对路径用于前端访问
                post.setImageUrl("/uploads/community/" + fileName);
            }
        } catch (IOException e) {
            log.error("文件上传失败: ", e);
            throw new RuntimeException("文件上传失败，请检查文件权限和路径");
        }

        communityPostService.addPost(post);
        return "redirect:toCommunity";
    }

    // 发表评论
    @RequestMapping("/addComment")
    @ResponseBody
    public Map<String, Object> addComment(CommunityCommentEntity comment, HttpSession session) {
        MemberEntity member = (MemberEntity) session.getAttribute("user");

        Map<String, Object> result = new HashMap<>();

        if (member == null) {
            result.put("success", false);
            result.put("msg", "请先登录");
            return result;
        }

        comment.setMemberId(member.getMemberAccount());
        comment.setMemberName(member.getMemberName());
        comment.setCreateTime(new Date());

        Boolean success  = communityCommentService.addComment(comment);
        if(success) {
            result.put("success", true);
            result.put("msg", "评论成功");
            result.put("comment", comment);
        }else {
            result.put("success", false);
            result.put("msg", "评论失败");
        }
        return result;
    }

    // 加载评论
    @RequestMapping("/getComments")
    @ResponseBody
    public List<CommunityCommentEntity> getComments(@RequestParam("postId") Long postId) {
        return communityCommentService.selectCommentsById(postId);
    }


//---------------------------------------------------------------------------------------------


    // 验证是否为图片文件
    private boolean isValidImageFile(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null &&
                (contentType.startsWith("image/") ||
                        Arrays.asList("jpg", "jpeg", "png", "gif").contains(
                                getFileNameExtension(file.getOriginalFilename())));
    }

    // 获取文件扩展名
    private String getFileNameExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) {
            return fileName.substring(lastDotIndex + 1).toLowerCase();
        }
        return "";
    }

}
